package org.example.Server.service.examination;

import lombok.extern.slf4j.Slf4j;
import org.example.Server.mapper.examination.ExamMapper;
import org.example.Server.mapper.examination.TeachExamMapper;
import org.example.Server.mapper.paper.PaperPersonalMapper;
import org.example.Server.mapper.question.QuestionMapper;
import org.example.Server.mapper.user.UserMapper;
import org.example.Server.model.examination.*;
import org.example.Server.model.paper.*;
import org.example.Server.model.question.Option;
import org.example.Server.model.question.Question;
import org.example.Server.model.semester.SemStu;
import org.example.Server.service.paper.PaperPersonalService;
import org.example.Server.utils.ResultAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

import static org.example.Server.utils.ExceptionEnum.SQL_ERROR;

@Service
@Slf4j
public class TeachExamService {
    @Autowired
    TeachExamMapper teachExamMapper;
    @Autowired
    ExamMapper examMapper;
    @Autowired
    PaperPersonalMapper paperPersonalMapper;
    @Autowired
    QuestionMapper questionMapper;
    @Autowired
    PaperPersonalService paperPersonalService;
    @Autowired
    private UserMapper userMapper;

    public ResultAPI addReadyPExam(TeachExamDTO teachExamDTO) {
        Integer techId = teachExamDTO.getTech_id();
        // 获取该试卷
        PaperQsIds paperQsIds = paperPersonalMapper.getPaperQsIdsById(teachExamDTO.getPaper_id());
        paperQsIds.getPaperHeader().setTech_id(techId);
        //添加试卷
        paperPersonalMapper.addPaperHeader(paperQsIds.getPaperHeader(), 0);
        Integer paperId = paperQsIds.getPaperHeader().getPaper_id();

        paperPersonalMapper.addPaperQsType(paperId);
        //set新试卷的id
        teachExamDTO.setPaper_id(paperId);
        //添加考试
        teachExamMapper.addExam(teachExamDTO);
        //批量复制题目
        List<Question> questionList = questionMapper.getQuestionByIds(paperQsIds.getQsIds());
        paperPersonalService.CopyQses(questionList, techId, paperId);
        return ResultAPI.success(teachExamDTO);
    }

    public ResultAPI addNewPExam(TeachExamDTO teachExamDTO) {
        ResultAPI result = null;
        try {
            //先把试卷给创建了
            paperPersonalMapper.addPaperHeader(teachExamDTO.getPaperHeader(), 0);
//            log.info("在线考试创建的试卷%d", teachExamDTO);
            //添加试卷题型
            paperPersonalMapper.addPaperQsType(teachExamDTO.getPaperHeader().getPaper_id());
            //获取试卷答题时长
            Integer duringTime = teachExamDTO.getPaperHeader().getDuring_time();
            if (duringTime != null) {
                teachExamDTO.setIs_during(true);
                teachExamDTO.setDuring_time(duringTime);
            }
            //获取新建试卷id
            Integer paper_id = teachExamDTO.getPaperHeader().getPaper_id();
            teachExamDTO.setPaper_id(paper_id);
            teachExamMapper.addExam(teachExamDTO);
            result = ResultAPI.success(teachExamDTO);
        } catch (Exception e) {
            result = ResultAPI.error(SQL_ERROR.getResultCode(), SQL_ERROR.getResultMsg());
            throw new RuntimeException(e);
        } finally {
            return result;
        }
    }

    public ResultAPI getTeachExamList(Integer semId, Integer status) {
        List<ExamShow> examShowList = examMapper.getExamList(semId, status);
        return ResultAPI.success(examShowList);
    }

    @Transactional(rollbackFor = Exception.class)
    public ResultAPI addPaperRule(ExamSetting examSetting) {
        try {
            // 第一步：插入试卷规则
            teachExamMapper.addPaperRule(examSetting);

            // 第二步：插入提醒信息
            // 0.增加、更新、删除列表
            List<ExamRemind> remindList = examSetting.getRemind_list();
            List<ExamRemind> remindDellist = examSetting.getRemind_dellist();
            List<ExamRemind> remindUpdatelist = examSetting.getRemind_updatelist();
            // 又要重新修bug！！！
            // 增加、删除、更新
            if (remindList != null && !remindList.isEmpty()) {
                teachExamMapper.addExamRemind(remindList);
            }
            if (remindDellist != null && !remindDellist.isEmpty()) {
                teachExamMapper.delExamRemind(remindDellist);
            }
            if (remindUpdatelist != null && !remindUpdatelist.isEmpty()) {
                teachExamMapper.updateExamRemind(remindUpdatelist);
            }

            return ResultAPI.success(examSetting);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("添加试卷规则失败", e);

            // 返回错误结果（无需手动抛出异常）
            return ResultAPI.error(SQL_ERROR.getResultCode(), SQL_ERROR.getResultMsg());
        }
    }

    public ResultAPI getPaperRule(Integer examId) {
        ResultAPI result = null;
        try {
            ExamSetting examSetting = teachExamMapper.getPaperRule(examId);
            result = ResultAPI.success(examSetting);
        } catch (Exception e) {
            result = ResultAPI.error(SQL_ERROR.getResultCode(), SQL_ERROR.getResultMsg());
            throw new RuntimeException(e);
        } finally {
            return result;
        }
    }


    public ResultAPI getPaperAnsList(Integer divisionId, Integer submitStatus, Integer markStatus, Integer examId) {
        ResultAPI result = null;
        List<ExamStu> examStuList = null;
        try {
            examStuList = teachExamMapper.getPaperAnsList(
                    divisionId, submitStatus, markStatus, examId
            );
            result = ResultAPI.success(examStuList);
        } catch (Exception e) {
            result = ResultAPI.error(SQL_ERROR.getResultCode(), SQL_ERROR.getResultMsg());
            log.info(e.getMessage());
            throw new RuntimeException(e);
        } finally {
            return result;
        }
    }

    /**
     * 批量删除考试
     *
     * @param ids
     * @return
     */
    public ResultAPI deleteExams(Integer[] ids) {
        ResultAPI result = null;
        try {
            teachExamMapper.deleteExamsByIds(ids);
            result = ResultAPI.success();
        } catch (Exception e) {
            result = ResultAPI.error(SQL_ERROR.getResultCode(), SQL_ERROR.getResultMsg());
            log.info(e.getMessage());
            throw new RuntimeException(e);
        } finally {
            return result;
        }
    }

    /**
     * 获取学生答题详情
     *
     * @param examStu
     * @return
     */
    public ResultAPI getExamStuDetail(ExamStu examStu) {
        Integer stuExamId = examStu.getStu_exam_id();
        Integer paperId = examStu.getPaper_id();
        Integer semId = examStu.getSem_id();
        ExamStuDetail examStuDetail = new ExamStuDetail();
        try {
            //获取试卷头
            PaperHeader paperHeader = paperPersonalMapper.getPaperHeaderById(paperId);
            examStuDetail.setPaperHeader(paperHeader);
            //获取学生信息
            SemStu student = teachExamMapper.getStuByStuExamId(stuExamId, semId);
            examStuDetail.setStudent(student);
            //获取试卷模块应得分以及学生得分
            List<ExamStuFormat> examStuFormat = teachExamMapper.getExamStuFormat(stuExamId, paperId);
            examStuDetail.setExamStuFormat(examStuFormat);
            //获取题目以及得分明细
            //再获得试卷题型-显示每一题内容（包括答案以及选项（选择题
            //获取题型map
            List<PaperFormat> qsFormatList = paperPersonalMapper.getPaperFormatById(paperId);
            //按照题型获取
            for (int i = 0; i < qsFormatList.size(); i++) {
                String qsType = qsFormatList.get(i).getQs_type();
                //分题型
                if (qsType.equals("qna")) {
                    //问答题
                    ExamQna qna = new ExamQna(qsFormatList.get(i));
                    List<ExamStuQna> qnas = teachExamMapper.getStuQandA(paperId, stuExamId);
                    qna.setItems(qnas);

                    if (qnas != null && !qnas.isEmpty()) {
                        examStuDetail.getQsList().add(qna);
                    }
                } else {
                    //选择类的
                    ExamSel paperSelect = new ExamSel(qsFormatList.get(i));
                    List<ExamStuSel> qSelects = teachExamMapper.getStuQSelect(paperId, qsType, stuExamId);
                    paperSelect.setItems(qSelects);
                    //需要展示答案ABCD:需要有两个for循环叠加
                    //这个强转我有点难绷
                    for (int j = 0; j < qSelects.size(); j++) {
                        ExamStuSel qSelect = qSelects.get(j);
                        String stu_ans = "";
                        String qs_ans = "";
                        for (int k = 0; k < qSelect.getOptions().size(); k++) {
                            Option option = qSelect.getOptions().get(k);
                            if (option.getStu_choosed()) {
                                stu_ans += (char) (k + 'A');
                            }
                            if (option.getIs_right()) {
                                qs_ans += (char) (k + 'A');
                            }
                        }
                        qSelect.setStu_ans(stu_ans);
                        qSelect.setQsel_ans(qs_ans);
                        log.info("标准答案：{}", qs_ans);
                        log.info("选择题答案：{}", qSelects.get(j).getQsel_ans());
                    }
                    if (!qSelects.isEmpty()) {
                        examStuDetail.getQsList().add(paperSelect);
                    }
                    log.info("答题详情{}", examStuDetail.getQsList());
                }

            }
            return ResultAPI.success(examStuDetail);
        } catch (Exception e) {
            log.error("获取答题详情失败", e);
            return ResultAPI.error(SQL_ERROR.getResultCode(), SQL_ERROR.getResultMsg());
        }
    }

    /**
     * 评阅学生成绩
     *
     * @param examStuQsDTO
     * @return
     */
    @Transactional
    public ResultAPI updateExamStu(ExamStuQsDTO examStuQsDTO) {
        List<ExamStuQs> examStuQs = examStuQsDTO.getExamStuQs();
        teachExamMapper.updateExamStu(examStuQs);
        //重新计算学生的成绩
        teachExamMapper.updateExamStuGetscore(examStuQsDTO.getStu_exam_id());
        //状态改为已评阅
        teachExamMapper.updateExamMark(examStuQsDTO.getStu_exam_id());
        return ResultAPI.success();
    }
}
